/*
 * @lc app=leetcode.cn id=703 lang=javascript
 *
 * [703] 数据流中的第 K 大元素
 */

// @lc code=start
/**
 * @param {number} k
 * @param {number[]} nums
 */
var KthLargest = function (k, nums) {
    nums.sort((a, b) => { return b - a })
    nums = nums.slice(0, k)
    this.nums = nums
    this.k = k
};

/** 
 * @param {number} val
 * @return {number}
 */
KthLargest.prototype.add = function (val) {
    let k = this.nums.length
    if (this.k == k) {
        if (val >= this.nums[k - 1]) {
            let i = k - 1
            while (i >= 0 && this.nums[i] < val) {
                this.nums[i + 1] = this.nums[i]
                i--
            }
            this.nums[i + 1] = val
            this.nums.length = k
            return this.nums[k - 1]
        } else {
            return this.nums[k - 1]
        }
    } else {
        this.nums.push(val)
        this.nums.sort((a,b)=>{return b-a})
        if (this.nums.length == this.k){return this.nums[this.k-1]} 
    }
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * var obj = new KthLargest(k, nums)
 * var param_1 = obj.add(val)
 */
// @lc code=end

